package com.jtxy.npms.controller;

import com.jtxy.npms.entity.Supervisor;
import com.jtxy.npms.utils.FileUtils;
import com.jtxy.npms.utils.Utils;
import javafx.fxml.FXML;
import javafx.scene.control.PasswordField;
import javafx.scene.control.RadioButton;
import javafx.scene.control.TextField;
import javafx.scene.control.ToggleGroup;

import java.io.IOException;
import java.util.Map;

public class RegisterViewController {
    @FXML
    private TextField txtTelId;
    @FXML
    private PasswordField txtPassword, txtConfirmPassword;
    @FXML
    private TextField txtName;
    @FXML
    private RadioButton male;
    @FXML
    private RadioButton female;
    @FXML
    private ToggleGroup genderGroup;

    //    界面初始化方法，启动时自动执行，方法原型是固定的，不能改写
    @FXML
    public void initialize() {
        genderGroup = new ToggleGroup();
        male.setToggleGroup(genderGroup);
        female.setToggleGroup(genderGroup);
    }

    //    注册的方法，用来保存监督员的所有信息
    public void saveSupervisor() {
        String telId = txtTelId.getText();//取到文本框的电话号码
        String password = txtPassword.getText();//取到文本框的密码
        String confirmPassword = txtConfirmPassword.getText();
        String name = txtName.getText();
//        通过选项组取到性别
        RadioButton gender = (RadioButton) genderGroup.getSelectedToggle();
//        判定密码是否一致，如果不一致，则提示用户
        if (!password.equals(confirmPassword)) {
//           弹出提示框
            Utils.showDialog("用户注册", "密码不一致！");
            return;
        }
        //密码一致时，打印所有控件的信息以测试绑定是否成功
        System.out.println(telId + password + confirmPassword + name + gender.getText());

//        新建一个supervisor对象
        Supervisor supervisor = new Supervisor(telId, password, name, gender.getText());
//        读取当前map，将supervisor对象保存到map集合中
        Map<String, Supervisor> map = FileUtils.readObject("supervisor.txt");
//        将supervisor对象保存到map集合中
        map.put(telId, supervisor);
//        将map集合写入到文件supervisor.txt中
        FileUtils.writeObject("supervisor.txt", map);
        Utils.showDialog("用户注册", "注册成功！");
        Utils.switchToView("loginView.fxml", txtName);
    }


    public void back() throws IOException {
        Utils.switchToView("loginView.fxml", txtName);
    }

}
